package psn.polaris.util;

import org.springframework.context.ApplicationContext;

import java.util.ArrayList;
import java.util.List;

public class SpringUtils {

    private static ApplicationContext context = null;

    /**
     * 根据Bean类型获取Bean名称
     * @param requireType   Bean类型
     * @return              Bean名称
     */
    public static String[] getSpringBeanNameByType(Class<?> requireType){
        return context.getBeanNamesForType(requireType);
    }

    /**
     * 根据Bean类型获取Bean
     * @param requireType   Bean类型
     * @return              Bean实例
     */
    public static<T> List<T> getSpringBeanByType(Class<T> requireType){
        String[] beanName = getSpringBeanNameByType(requireType);
        List<T> ret = new ArrayList<>(beanName.length);
        for (String bean : beanName) {
            ret.add(context.getBean(bean, requireType));
        }
        return ret;
    }

    /**
     * 根据Bean类型获取Bean
     * @param beanName      Bean名称
     * @param requireType   Bean类型
     * @return              Bean实例
     */
    public static<T> T getSpringBeanByType(String beanName, Class<T> requireType){
        return context.getBean(beanName, requireType);
    }

    /**
     * 注册Spring上下文
     * @param context   Spring上下文
     */
    public static void registerContext(ApplicationContext context){
        if(null==SpringUtils.context){
            SpringUtils.context = context;
        }
    }

}
